<template>
  <div class="container">
    <Breadcrumb :items="['站点管理', '充电桩管理', '转发日志']" />
    <a-card class="general-card" title="转发日志查询">
      <!-- 搜索表单 -->
      <a-form
        :model="searchForm"
        label-align="left"
        :label-col-props="{ span: 6 }"
        :wrapper-col-props="{ span: 18 }"
        label-layout="inline"
      >
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item field="deviceName" label="充电桩编号">
              <a-input
                v-model="searchForm.deviceName"
                placeholder="请输入充电桩编号"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item field="forwardDeviceName" label="平台设备编号">
              <a-input
                v-model="searchForm.forwardDeviceName"
                placeholder="请输入平台设备编号"
                allow-clear
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item field="startTime" label="开始时间">
              <a-date-picker
                v-model="searchForm.startTime"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择开始时间"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item field="endTime" label="结束时间">
              <a-date-picker
                v-model="searchForm.endTime"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择结束时间"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-space>
              <a-button type="primary" @click="search">
                <template #icon>
                  <icon-search />
                </template>
                搜索
              </a-button>
              <a-button @click="reset">
                <template #icon>
                  <icon-refresh />
                </template>
                重置
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form>

      <!-- 日志列表 -->
      <a-table
        :loading="loading"
        :data="logList"
        :pagination="pagination"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
        stripe
      >
        <template #columns>
          <a-table-column title="序号" :width="80">
            <template #cell="{ rowIndex }">
              {{ (pagination.current - 1) * pagination.pageSize + rowIndex + 1 }}
            </template>
          </a-table-column>
          <a-table-column title="原始设备编号" :width="150">
            <template #cell="{ record }">
              {{ record.deviceName }}
            </template>
          </a-table-column>
          <a-table-column title="转发设备编号" :width="150">
            <template #cell="{ record }">
              {{ record.forwardDeviceName }}
            </template>
          </a-table-column>
          <a-table-column title="日志类型" :width="120">
            <template #cell="{ record }">
              <a-tag :color="getLogTypeColor(record.logType)">
                {{ getLogTypeName(record.logType) }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="平台服务器信息" :width="200">
            <template #cell="{ record }">
              {{ record.serverInfo }}
            </template>
          </a-table-column>
          <a-table-column title="创建时间" :width="180">
            <template #cell="{ record }">
              {{ record.createDate }}
            </template>
          </a-table-column>
          <a-table-column title="操作" :width="120" fixed="right">
            <template #cell="{ record }">
              <a-space>
                <a-button type="text" size="small" @click="viewDetail(record)">
                  详情
                </a-button>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 日志详情对话框 -->
    <a-modal
      v-model:visible="detailVisible"
      title="日志详情"
      @cancel="detailVisible = false"
      :footer="false"
      width="800px"
    >
      <div v-if="currentLog" class="log-detail">
        <a-descriptions :column="1" bordered size="large">
          <a-descriptions-item label="原始设备编号">{{ currentLog.deviceName }}</a-descriptions-item>
          <a-descriptions-item label="转发设备编号">{{ currentLog.forwardDeviceName }}</a-descriptions-item>
          <a-descriptions-item label="日志类型">
            <a-tag :color="getLogTypeColor(currentLog.logType)">
              {{ getLogTypeName(currentLog.logType) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="平台服务器信息">{{ currentLog.serverInfo }}</a-descriptions-item>
          <a-descriptions-item label="创建时间">{{ currentLog.createDate }}</a-descriptions-item>
          <a-descriptions-item label="设备原始消息">
            <pre class="message-content">{{ currentLog.iotMsg }}</pre>
          </a-descriptions-item>
          <a-descriptions-item label="转发数据">
            <pre class="message-content">{{ currentLog.forwardMsg }}</pre>
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { Message } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import axios from 'axios';
import dayjs from 'dayjs';
import { useRouter } from 'vue-router';

// 日志数据接口
interface LogItem {
  deviceName: string;
  forwardDeviceName: string;
  logType: number;
  forwardMsg: string;
  serverInfo: string;
  createDate: string;
  iotMsg: string;
}

// 日志类型
const LogType = {
  REPORT: 0,      // 上报
  SEND: 1,        // 下发
  FORWARD: 2,     // 转发
  SERVER_SEND: 3  // 三方服务器下发
} as const;

// 获取日志类型名称
function getLogTypeName(type: number) {
  switch (type) {
    case LogType.REPORT:
      return '上报数据';
    case LogType.SEND:
      return '下发数据';
    case LogType.FORWARD:
      return '转发数据';
    case LogType.SERVER_SEND:
      return '三方平台下发';
    default:
      return '未知';
  }
}

// 获取日志类型标签颜色
function getLogTypeColor(type: number) {
  switch (type) {
    case LogType.REPORT:
      return 'blue';    // 上报 - 蓝色
    case LogType.SEND:
      return 'green';   // 下发 - 绿色
    case LogType.FORWARD:
      return 'orange';  // 转发 - 橙色
    case LogType.SERVER_SEND:
      return 'purple';  // 三方服务器下发 - 紫色
    default:
      return 'gray';
  }
}

// 加载状态
const { loading, setLoading } = useLoading();

// 对话框状态
const detailVisible = ref(false);
const currentLog = ref<LogItem | null>(null);

// 日志列表
const logList = ref<LogItem[]>([]);

// 分页
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: true,
  showJumper: true,
  showPageSize: true,
});

// 搜索表单
const searchForm = reactive({
  deviceName: '',
  forwardDeviceName: '',
  logType: undefined as number | undefined,
  startTime: undefined as Date | undefined,
  endTime: undefined as Date | undefined,
});

// 获取日志列表数据
async function fetchData() {
  // 如果没有输入充电桩编号和平台设备编号，则不调用接口
  if (!searchForm.deviceName && !searchForm.forwardDeviceName) {
    return;
  }
  
  setLoading(true);
  try {
    const params = {
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      deviceName: searchForm.deviceName,
      forwardDeviceName: searchForm.forwardDeviceName,
      createDateStart: searchForm.startTime ? dayjs(searchForm.startTime).format('YYYY-MM-DD HH:mm:ss') : undefined,
      createDateEnd: searchForm.endTime ? dayjs(searchForm.endTime).format('YYYY-MM-DD HH:mm:ss') : undefined,
    };
    
    const response = await axios.get('/api/v1/sls/log/list', { params });
    logList.value = response.data.records;
    pagination.total = response.data.total;
  } catch (error) {
    console.error('获取日志列表失败:', error);
    Message.error('获取日志列表失败');
  } finally {
    setLoading(false);
  }
}

// 分页变化
function onPageChange(current: number) {
  pagination.current = current;
  fetchData();
}

// 每页条数变化
function onPageSizeChange(pageSize: number) {
  pagination.pageSize = pageSize;
  pagination.current = 1;
  fetchData();
}

// 搜索
function search() {
  if (!searchForm.deviceName && !searchForm.forwardDeviceName) {
    Message.warning('请输入充电桩编号或平台设备编号');
    return;
  }
  pagination.current = 1;
  fetchData();
}

// 重置搜索条件
function reset() {
  searchForm.deviceName = '';
  searchForm.forwardDeviceName = '';
  searchForm.startTime = undefined;
  searchForm.endTime = undefined;
  pagination.current = 1;
  // 重置时不调用接口
}

// 查看日志详情
function viewDetail(log: LogItem) {
  currentLog.value = log;
  detailVisible.value = true;
}

onMounted(() => {
  // 从路由参数中获取设备ID和名称
  const route = useRouter().currentRoute.value;
  if (route.query.deviceId) {
    // 获取充电桩编号(pileCode)
    if (route.query.pileCode) {
      searchForm.deviceName = route.query.pileCode as string;
    } else if (route.query.deviceName) {
      // 如果没有pileCode，则使用deviceName
      searchForm.deviceName = route.query.deviceName as string;
    }
  }
  
  // 如果有设备编号，自动搜索
  if (searchForm.deviceName) {
    search();
  } else {
    // 初始化时不调用接口
    logList.value = [];
    pagination.total = 0;
  }
});
</script>

<style scoped lang="less">
.container {
  padding: 0 20px 20px 20px;
}

.log-detail {
  :deep(.arco-descriptions) {
    background-color: var(--color-bg-2);
  }
  
  .message-content {
    margin: 0;
    padding: 8px;
    background-color: var(--color-fill-2);
    border-radius: 4px;
    font-family: monospace;
    white-space: pre-wrap;
    word-break: break-all;
    max-height: 300px;
    overflow-y: auto;
  }
}
</style> 